package com.woniuxy.controller;

import com.woniuxy.entity.User;
import com.woniuxy.entity.utils.ResponseEntity;
import com.woniuxy.jwt.JWTUtils;
import com.woniuxy.service.AuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/auth")
public class AuthController {

    @Autowired
    AuthService authService;

    @Resource
    RedisTemplate redisTemplate;
    @GetMapping("/login")
    public ResponseEntity login(User user) {
        User dbuser = authService.findUser(user);
        if (Objects.nonNull(dbuser) && dbuser.getPassword().equals(user.getPassword())) {
            String token = JWTUtils.generateToken(user.getUsername());
            ResponseEntity success = new ResponseEntity(dbuser);
            success.put("token", token);
            String refreshToken= UUID.randomUUID().toString();
            redisTemplate.opsForValue().set(refreshToken,dbuser);
            redisTemplate.expire(refreshToken,60, TimeUnit.MINUTES);
            success.put("refreshToken",refreshToken);
            return success;
        } else {
            return ResponseEntity.ERROR;
        }
    }

    @PutMapping("/")
    public ResponseEntity updateUser(@RequestBody User user){
        return new ResponseEntity(authService.updateUser(user));
    }
    @DeleteMapping("/clearCache")
    public ResponseEntity clearCache(){
        authService.clearCache();
        return new ResponseEntity("清除成功！");
    }
}
